<?php namespace App\Controllers;

use \App\App;

class Comment extends App
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $page = $this->request->post('page') ?: 0;
    }

    public function post()
    {
        $commentModel = new \App\Models\Comment();
        $content = $this->request->post('content');
        $storyID = $this->request->post("id");
        $replyID = $this->request->post("reply") ?: 0;

        if (!$this->user) {
            $this->showJson("用户尚未登录，请登录后重新发表。", 'Error');
        }
        $comment = [
            "content" => htmlspecialchars($content),
            "story" => $storyID,
            "user" => $this->user['id'],
            "reply" => $replyID,
            "replyNum" => 0,
            "date" => time(),
            "commend" => 0,
        ];

        if ($replyID) {
            $commentReply = $commentModel->find($replyID);
            $commentReply['replyNum'] += 1;
            $commentModel->save($commentReply);
        }

        $commentModel->save($comment);
        //用于AJAX直接显示
        $view = new \System\View($this->config->view);
        $comment['username'] = $this->user['username'];
        $comment['avatar'] = $this->user['avatar'];
        $view->comment = $comment;
        $view->assets = $this->config->baseUrl . "/assets";
        $this->showJson([
            "status" => "Success",
            "message" => "发表评论成功",
            "reply" => $replyID,
            "html" => $view->display("/front/comment/comment")->tostring(),
        ]);
    }

    public function get($id)
    {
        $commentModel = new \App\Models\Comment();
        $view = new \System\View($this->config->view);
        $view->assets = $this->config->baseUrl . "/assets";
        $replys = $commentModel->select("comment.*,users.username,users.avatar")
            ->join("users", "users.id=comment.user")
            ->where("reply", $id)
            ->order("date", "DESC")
            ->get();
        $html = "";
        foreach ($replys as $reply) {
            $view->comment = $reply;
            $html .= $view->display("/front/comment/comment")->tostring();
        }
        echo $html;
    }
}